package com.itheima.leyou.service.impl;

import com.itheima.leyou.clients.UserClient;
import com.itheima.leyou.common.exception.LyException;
import com.itheima.leyou.constants.JwtConstants;
import com.itheima.leyou.dto.UserDTO;
import com.itheima.leyou.dto.UserDetail;
import com.itheima.leyou.service.UserAuthService;
import com.itheima.leyou.utils.JwtUtils;
import feign.FeignException;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Service
public class UserAuthServiceImpl  implements UserAuthService {

   //构造函数注入
    private final UserClient userClient;
    private final JwtUtils jwtUtils;
    public UserAuthServiceImpl(UserClient userClient,JwtUtils jwtUtils){
        this.jwtUtils=jwtUtils;
        this.userClient=userClient;
    }


    @Override
    public void login(String username, String password, HttpServletResponse response) {
        try {
            UserDTO userDTO = userClient.loginUser(username, password);
            if(userDTO==null){
                throw new LyException(400,"登录失败");
            }
            //登录成功，生成jwt
            //准备用户信息
            UserDetail userDetail = UserDetail.of(userDTO.getId(), userDTO.getUsername());
            //生成jwt
            String jwt = jwtUtils.createJwt(userDetail);
            //写入到cookie中
            writeJwtToCookie(response, jwt);
        } catch (FeignException e) {
            // 把远程调用异常转换抛出
            throw new LyException(e.status(), e.getMessage());
        }
    }

    private void writeJwtToCookie(HttpServletResponse response, String token) {
        Cookie cookie = new Cookie(JwtConstants.COOKIE_NAME, token);
        // cookie的作用域
        cookie.setDomain(JwtConstants.DOMAIN);
        // 是否禁止JS操作cookie，避免XSS攻击
        cookie.setHttpOnly(true);
        // cookie作用的路径，/代表一切路径
        cookie.setPath("/");
        response.addCookie(cookie);
    }

}
